const TagConfig = {
	CONTAINER_CLASS: 'filter-tabs',
	ITEM_CLASS: 'filter-tab'
}

class Tag {
	constructor(options) {
		this.data = options.data;
		this.activeIndex = options.active || 0;
		this.container = document.querySelector(options.container);
		this.onChange = options.onChange || function() {}
		this.init();
	}

	init() {
		this.render();
		this.addStyles();
		this.bindEvents();
	}

	render() {
		if (this.data.length == 0) return;
		const html = this.data.map((item, index) =>
			this.generateItem(item, index)
		).join('');
		this.container.innerHTML = `<div class="filter-tabs">${html}</div>`;
	}

	generateItem(item, index) {
		const isActive = index === this.activeIndex;
		return `<button class="${TagConfig.ITEM_CLASS}  ${isActive ? 'active':''}" data-index="${index}">${item.value}</button>`
	}

	bindEvents() {
		this.container.addEventListener('click', e => {
			this.getAllSiblings(e.target).forEach(el => {
				el.classList.remove('active');
			});
			if (e.target.classList.contains(TagConfig.ITEM_CLASS)) {
				e.target.classList.add('active');
				let index = e.target.dataset.index;
				this.activeIndex = index;
				let item = this.data[index];
				this.onChange({
					activeIndex: index,
					...item
				});
			}
		})
	}

	/**
	 * @param {Object} element
	 * 分别向前和向后查找相邻兄弟节点
	 */
	getAllSiblings(element) {
		const siblings = [];
		let prev = element.previousElementSibling;
		let next = element.nextElementSibling;
		while (prev) {
			siblings.unshift(prev);
			prev = prev.previousElementSibling;
		}
		while (next) {
			siblings.push(next);
			next = next.nextElementSibling;
		}
		return siblings;
	}


	update(newData) {
		this.data = newData;
		this.activeIndex = 0;
		this.render();
	}

	addStyles() {
		this.styleElement = document.createElement('style');
		this.styleElement.textContent = `
		  .${TagConfig.CONTAINER_CLASS} {
		  	/*background: var(--bg-title-bar);*/
		  	display: flex;
		  	flex-direction: row;
		  	overflow-x: auto;
		  	/* flex-wrap: wrap; */
		  	gap: var(--gap);
		  	scrollbar-width: none;
		  	-ms-overflow-style: none;
		  	-webkit-overflow-scrolling: touch;
		  }
		  
		  .${TagConfig.CONTAINER_CLASS}::-webkit-scrollbar {
		  	display: none;
		  }
		  
		  .${TagConfig.ITEM_CLASS} {
		  	padding: 0.5rem 1.2rem;
		  	border-radius: calc(var(--gap) * 3);
		  	border: none;
		  	white-space: nowrap;
		  	font-size: var(--font-size-primary);
		  	color: var(--color-second);
		  }
		  
		  .${TagConfig.ITEM_CLASS}.active {
		  	background: var(--primary);
		  	color: white;
		  }
		`;
		document.head.appendChild(this.styleElement);
	}
}
